import { login } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken()
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    setToken(token)
    state.token = token
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    commit('SET_TOKEN', res.data.token)
    router.replace('/')
  },
  logout(context) {
    context.commit('removeToken') // 删除token
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
